﻿using Vampirewal.Admin.ShareCommon;

namespace Vampirewal.Admin.Client.ViewModels.Services;

/// <summary>
/// 更新服务
/// </summary>
public interface IUpgradeService
{
    /// <summary>
    /// 更新
    /// </summary>
    void Update();
}

/// <summary>
/// 更新服务
/// </summary>
public class UpgradeService : IUpgradeService
{
    private IRpcService RpcService { get; set; }
    private IVampirewalCoreDialogMessage Dialog { get; set; }

    private IApplicationService ApplicationService { get; set; }

    private AppBaseOptions BaseOption { get; set; }
    private UpdateOptions UpOption { get; set; }

    public UpgradeService(IRpcService rpcService, IVampirewalCoreDialogMessage dialog, IApplicationService application)
    {
        Dialog = dialog;
        RpcService = rpcService;
        ApplicationService= application;

        UpOption = VampirewalCoreContext.GetInstance().GetOptions<UpdateOptions>();
        BaseOption = VampirewalCoreContext.GetInstance().GetOptions<AppBaseOptions>();
    }

    /// <summary>
    /// 验证服务器版本和本地版本
    /// </summary>
    /// <returns></returns>
    private bool CheckVersion(string ServerVersion)
    {
        //先处理服务器的版本号
        string[] ServerStrs = ServerVersion.Split('.');
        int Server1 = Convert.ToInt32(ServerStrs[0]);
        int Server2 = Convert.ToInt32(ServerStrs[1]);
        int Server3 = Convert.ToInt32(ServerStrs[2]);
        int Server4 = Convert.ToInt32(ServerStrs[3]);

        //处理客户端版本号
        string[] ClientStrs = BaseOption.AppVersion.Split('.');
        int Client1 = Convert.ToInt32(ClientStrs[0]);
        int Client2 = Convert.ToInt32(ClientStrs[1]);
        int Client3 = Convert.ToInt32(ClientStrs[2]);
        int Client4 = Convert.ToInt32(ClientStrs[3]);

        //验证
        if (Server1 > Client1)
        {
            return true;
        }
        else if (Server1 == Client1)
        {
            if (Server2 > Client2)
            {
                return true;
            }
            else if (Server2 == Client2)
            {
                if (Server3 > Client3)
                {
                    return true;
                }
                else if (Server3 == Client3)
                {
                    if (Server4 > Client4)
                    {
                        return true;
                    }
                    else if (Server4 == Client4)
                    {
                        return false;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    public void Update()
    {
        if (!File.Exists($"{AppDomain.CurrentDomain.BaseDirectory}Vampirewal.Admin.Update.exe"))
        {
            //Dialog.ShowPopupWindow("自动更新程序未找到！", WindowsManager.GetInstance().MainWindow, MessageType.Error, true);
            Dialog.ShowPopupWindow(new Core.WindoSetting.PopupWindowSetting()
            {
                Message= "自动更新程序未找到！",
                OwnerWindow= WindowsManager.GetInstance().MainWindow,
                Type= Core.WindoSetting.MessageType.Error,
                IsKeepOpen= true,
            });
        }
        else
        {
            RpcService.CallApi<Sys_AppVersion>(RpcMethod.GetLastVersion, InvokeOptionUtil.Fast_WaitInvoke_10s, response =>
            {
                if (CheckVersion(response.Version))
                {
                    //打开自动更新程序
                    Process m_Process = new Process();
                    m_Process.StartInfo.FileName = $"{AppDomain.CurrentDomain.BaseDirectory}Vampirewal.Admin.Update.exe";
                    m_Process.Start();

                    ApplicationService.Shutdown();
                }
                else
                {
                    if (File.Exists($"{AppDomain.CurrentDomain.BaseDirectory}App{BaseOption.AppVersion}.zip"))
                    {
                        File.Delete($"{AppDomain.CurrentDomain.BaseDirectory}App{BaseOption.AppVersion}.zip");
                    }
                }
            }, ex =>
            {
                //Dialog.ShowPopupWindow($"版本获取异常，{ex}", WindowsManager.GetInstance().MainWindow, Vampirewal.Core.WpfTheme.WindowStyle.MessageType.Error);
                Dialog.ShowPopupWindow(new Core.WindoSetting.PopupWindowSetting()
                {
                    Message= $"版本获取异常，{ex}",
                    OwnerWindow= WindowsManager.GetInstance().MainWindow,
                    Type = Core.WindoSetting.MessageType.Error
                });
            });
        }
    }
}